package com.kancy.streamplus.channel;

import com.kancy.emailplus.spring.boot.service.EmailplusService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.annotation.Order;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * EmailNoticePollingMessageExceptionHandler
 * <p>
 *
 * @author: kancy
 * @date: 2020/3/23 10:52
 **/
@Order(100)
@ConditionalOnClass({EmailplusService.class})
public class EmailNoticePollingMessageExceptionHandler implements PollingMessageExceptionHandler{
    private final EmailplusService emailplusService;

    public EmailNoticePollingMessageExceptionHandler(EmailplusService emailplusService) {
        this.emailplusService = emailplusService;
    }

    /**
     * 处理异常
     *
     * @param message
     * @param e
     */
    @Override
    public void onException(Message<?> message, Exception e) {
        MessageHeaders messageHeaders = message.getHeaders();
        if (messageHeaders.containsKey(PollingMessage.EMAIL_KEY)){
            // 如果消息重试结束，发邮件
            emailplusService.sendTemplateEmail(
                    messageHeaders.get(PollingMessage.EMAIL_KEY, String.class), getTemplateData(message, e));
        }
    }

    private Map<String, Object> getTemplateData(Message<?> message, Exception e) {
        return new HashMap<>();
    }
}
